<template>
  <div>

    <div class="filter-container" style="margin:30px;">
      <el-input placeholder="标题" v-model="searchData" style="width: 200px;padding-right:20px" class="filter-item"></el-input>
      <!--      <el-input placeholder="作者" v-model="searchAuthor" style="width: 200px;padding:20px" class="filter-item"></el-input>-->

      <el-button @click="filterData" class="filter-item">查询博客</el-button>
      <el-button type="primary" class="filter-item" @click="handleAdd($route.query.nClass)">发布博客
      </el-button>

      <el-button @click="fromCommit()" style="" type="danger" class="filter-item">删除选中项</el-button>

    </div>

    <div>
      <el-table
          ref="multipleTable"
          :data="tableData.filter(data => !search || data.title.toLowerCase().includes(search.toLowerCase()))"
          stripe
          tooltip-effect="dark"
          style="width: 100%"
          current-row-key="id"
          @selection-change="handleSelectionChange"
          height="500px">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
<!--        <el-table-column-->
<!--            type="index"-->
<!--            align="center"-->
<!--            width="55"-->
<!--            label="序号">-->
<!--        </el-table-column>-->
        <el-table-column
            align="center"
            prop="title"
            label="标题">
        </el-table-column>
        <el-table-column
            label="预览图"
            prop="path"
            align="center">
          <template slot-scope="scope">
            <img width="100" :src="scope.row.path" />
          </template>
        </el-table-column>

        <el-table-column
            label="浏览量"
            prop="view"
            align="center">
          <!--        <template slot-scope="scope"><a :href=scope.row.url>{{ scope.row.nTitle }}</a></template>-->
        </el-table-column>
<!--        <el-table-column-->
<!--            label="状态"-->
<!--            prop="nDate"-->
<!--            width="100"-->
<!--            align="center">-->
<!--          &lt;!&ndash;        <template slot-scope="scope">{{ scope.row.nDate }}</template>&ndash;&gt;-->
<!--        </el-table-column>-->
        <el-table-column
            label="博客分类"
            prop="categoryId"
            align="center">
          <template slot-scope="scope">
              <span v-for="category in categorys " v-if="category.id === scope.row.categoryId">
                {{ category.categoryName }}
              </span>
          </template>
<!--                  <template slot-scope="scope">{{ scope.row.nDate }}</template>-->
        </el-table-column>
        <el-table-column
            label="添加时间"
            prop="updateTime"
            align="center">
          <!--        <template slot-scope="scope">{{ scope.row.nDate }}</template>-->
        </el-table-column>
        <el-table-column
            label="标签"
            prop="tags"
            align="center">
          <template slot-scope="scope">
            <el-tag
                v-for="(tag, index) in JSON.parse(scope.row.tags)"
                :key="index"
            >
              {{ tag }}
            </el-tag>
          </template>

        </el-table-column>

        <el-table-column label="操作" align="center" width="200">

          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>

          </template>

        </el-table-column>
      </el-table>
    </div>

    <!--编辑弹窗-->
    <div class="update">
      <el-dialog title="文档信息" :visible.sync="dialogFormVisible0" width="70%" top="20px">
        <!--        加入“v-if"，是为了每次打开和关闭弹窗动态创建和销毁组件，更新组件数据       -->
        <UpdateMassage v-bind:dialogFormVisible0="dialogFormVisible0" :shutdown.sync="dialogFormVisible0"
                       v-if="dialogFormVisible0===true" :oldRuleForm="JSON.stringify(this.ruleForm)" ></UpdateMassage>
      </el-dialog>
    </div>

    <div class="add">
      <el-dialog title="文档信息" :visible.sync="dialogFormVisibleAdd" width="70%" top="20px">
        <!--        加入“v-if"，是为了每次打开和关闭弹窗动态创建和销毁组件，更新组件数据       -->
        <AddNews v-bind:dialogFormVisibleAdd="dialogFormVisibleAdd" :shutdown.sync="dialogFormVisibleAdd"
                 v-if="dialogFormVisibleAdd===true"></AddNews>
      </el-dialog>
    </div>


    <!--分页组件-->
    <div class="pagination-container">
      <!--      <el-button type="primary" class="butT" @click="dialogFormVisible2 = true" style="float: left;margin-left: 30px">上传附件</el-button>-->
      <el-pagination
          class="pagiantion"

          @current-change="handleCurrentChange"

          :current-page="pagination.currentPage"

          :page-size="pagination.pageSize"

          layout="total, prev, pager, next, jumper"

          :total="pagination.total">
      </el-pagination>
    </div>


  </div>
</template>
<script>
import UpdateMassage from "@/views/UpdateMassage";
import AddNews from "@/views/addNews";

export default {
  name: 'MassagesComponent',
  components: {AddNews, UpdateMassage},
  computed: {
    key() {
      return this.$route.path + Math.random();
    }
  },
  data() {
    return {
      categorys:[],
      dialogFormVisibleAdd: false,
      search: '',
      searchData: '',
      searchAuthor: '',
      fileList: [],
      tableData: [],
      pagination: {//分页相关模型数据
        currentPage: 1,//当前页码
        pageSize: 10,//每页显示的记录数
        total: 0,//总记录数
        nTitle: "",//查询条件
        nAuthor: "",
        nClass: ""
      },
      dialogFormVisible4Edit: false,
      dialogFormVisible0: false,
      dialogFormVisible2: false,
      //选择本地文档的文档信息，用于上传给后台
      ruleForm: {
        category: "1",
        notice: "",
        name: "",
        news: false,
        author: "",
        text: ""
      },
      //编辑框内回显的内容，从后台请求
      formData: {
        // category:"2",
        // notice:"",
        // news:false,
        // name:"测试",
        // author:"测试",
        // text:"<p>你好</p>"
      },
      //updateForm：用于测试回显信息
      updateForm: {
        category: "2",
        notice: "测试回显示",
        name: "测试",
        news: false,
        author: "测试",
        text: "<p>测试回显</p>"
      },
      clearForm: {
        category: "1",
        notice: "",
        name: "",
        news: false,
        author: "",
        text: ""
      },

      multipleSelection: [],
      rules: {
        name: [
          {required: true, message: '请输入文档名称', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        author: [
          {required: true, message: '请输入作者名称', trigger: 'blur'},
          {min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur'}
        ],
      },

    }
  },

  methods: {
    // 文件上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    //多选
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

      //新批量删除
    async delUsers(){
      //筛选被勾选的数据
      let toDelUsers = this.tableData.filter(user=>user.isChoose==true);
      //获取由被勾选用户数据构成的id的数组
      let ids = toDelUsers.map(user=>user.id);
      //批量删除
      let result =await this.$http.userHttp.delUsers({
        // ids:ids
        ids
      })
      if(result.data.data >0){
        this.$message({
          message:"批量删除成功",
          type:'success'
        });
      }else{
        this.$message({
          message:"批量删除失败",
          type:'error'
        })
      }
      //重新获取数据并渲染
      // this.getAllUsers();
    },

    //旧。批量删除
    fromCommit() {
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
        var param = ''
        for (var i = 0; i < this.multipleSelection.length; i++) {
          param += this.multipleSelection[i].id + ','
          // param.append("nId",this.multipleSelection[i].nId)
        }
        // console.log("parma:::::")
        this.$axios.post("/tbBlog/delBlogs?ids=" + param).then(
            (res) => {
              if (res.data.code === 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error("删除失败!");
              }
            }
        ).finally(() => {
          this.getAll();
        })
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },

    handleDelete(row) {
      this.$confirm("此操作永久删除当前信息，是否继续？", "提示", {type: "info"}).then(() => {
        this.$axios.post("/tbBlog/delBlogs?ids=" + row.id).then(
            (res) => {
              if (res.data.code === 200) {
                this.$message.success("删除成功");
              } else {
                this.$message.error("删除失败!");
              }
            }
        ).finally(() => {
          this.getAll()
          // this.$router.push({path:'/allMessages',query:{nClass:this.$route.query.nClass}})
        })
      }).catch(() => {
        this.$message.info("取消操作");
      });
    },

    filterData() {
      // let a = this.searchData;
      // this.search = a;
      let param = "&title="+this.searchData;
      this.$axios.get("/tbBlog/pagin?pageNum=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize + param).then((res) => {
        this.pagination.total = res.data.data.count;
        console.log("searchdate");
        this.tableData = res.data.data.list;
        // console.log(this.tableData);

        // for(var i in this.tableData){
        //   this.tableData[i].nDate = this.tableData[i].nDate.substr(0,19)
        // }

      });
    },

    //获取所有消息
    getAll() {
      let param = "";
      this.$axios.get("/tbBlog/pagin?pageNum=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize + param).then((res) => {
        this.pagination.total = res.data.data.count;
        console.log("打印");
        this.tableData = res.data.data.list;
        // console.log(this.tableData);

        // for(var i in this.tableData){
        //   this.tableData[i].nDate = this.tableData[i].nDate.substr(0,19)
        // }

      });
    },
    //切换页码
    handleCurrentChange(currentPage) {
      //修改页码值为当前选中的页码值
      this.pagination.currentPage = currentPage;
      //执行查询
      this.getAll();
    },
    //弹出编辑窗口
    handleUpdate(row) {
      //开始使用的是路由配合router-view来改变弹窗中编辑和新增呈现不同数据，但是发现组件push路由后，除非这个父页面摧毁或路由其他子组件，路由的子组件不会自动摧毁，
      //所以先点开编辑进行路由，组件就生成了，再点击添加，则还是同一个组件，组件内的数据不会改变。
      //当使用v-if后，并可以根据true或false来生成和销毁组件，并根据传递参数呈现不同数据
      // this.$router.push({path:'/addText',query:{form:JSON.stringify(this.text)}})
      //开始直接使用this.ruleForm=this.updateForm，发现会让ruleForm指向updateForm对象，使两个地址相同，成为同一个对象，
      // 从而使ruleForm在data()中的数据丢失，而成为和updateForm的数据相同
      // let a = this.updateForm
      this.ruleForm = row;
      this.dialogFormVisible0 = true
    },
    handleAdd() {
      // console.log('增加文档测试nclass:')
      // this.$router.push({path:'/addText',query:{form:JSON.stringify(this.ruleForm)}})
      // console.log(nClass)

      //这里花费了很多时间来调整，开始直接将ruleForm的全部属性一一赋值为空，但是会产生连锁反应，这个对象改变了
      //后来使用变量b和clearForm来产生新对象再赋值的方式，不会对原对象产生污染
      let b = this.clearForm
      this.ruleForm = b
      this.dialogFormVisibleAdd = true

    },
    success(res) {
      this.dialogFormVisibleAdd = res;
    },
    getCategorys(){
      this.$axios.get("http://localhost:8081/Category/findall")
          .then(response => {
            this.categorys = response.data;
          })
          .catch(error => {
            this.$message.error("获取分类失败，请联系管理员")
          });
      // this.categorys=[{name:"前端",id:1},{name:"后端",id:2},{name:"全栈",id:3}]
    },
  },
  watch: {
    dialogFormVisible0() {
      if (this.dialogFormVisible0 === false) {
        this.getAll();
      }
    },
    dialogFormVisibleAdd() {
      if (this.dialogFormVisibleAdd === false) {
        this.getAll();
      }
    }

  },
  mounted() {
    this.getAll();
    this.getCategorys();
  }
}

</script>
<style>
.filter-item{
  /*float: left;*/
  /*margin-left: 10px;*/
}
</style>
